package com.zixun.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.zixun.Models.DiaryInfo;
import com.zixun.R;
import com.zixun.adapter.DiaryAdapter;
import com.zixun.db.DatabaseUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 作者：郭郭
 * 心情日记
 */

public class DiaryActivity extends Activity {


    private TextView center_text;
    private RecyclerView rlv_content;
    private Button btn_add;
    private DatabaseUtil databaseUtil;

    private int diaryFlag = 1;//请求心情

    private List<DiaryInfo> diaryInfos;
    private DiaryAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_layout);

        initView();
        initData();
    }

    private void initView() {
        center_text = (TextView) findViewById(R.id.center_text);
        rlv_content = (RecyclerView) findViewById(R.id.rlv_content);
        btn_add = (Button) findViewById(R.id.btn_add);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rlv_content.setLayoutManager(linearLayoutManager);
    }

    private void initData() {
        databaseUtil = new DatabaseUtil(DiaryActivity.this);
        center_text.setText("心情日记");
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DiaryActivity.this, NewsActivity.class);
                startActivityForResult(intent, diaryFlag);
            }
        });

        diaryInfos = databaseUtil.queryAll1Diary();
        if (diaryInfos != null && diaryInfos.size() > 0) {
            DiaryAdapter adapter = new DiaryAdapter(DiaryActivity.this, diaryInfos);
            rlv_content.setAdapter(adapter);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == diaryFlag && resultCode == diaryFlag) {
            final DiaryInfo diaryInfo = new DiaryInfo();
            diaryInfo.setDescription(data.getStringExtra("description"));
            //添加心情日记 插入数据库
            databaseUtil.insertDiary(diaryInfo);
            if (diaryInfos == null) {
                diaryInfos = new ArrayList<DiaryInfo>();
            }
            diaryInfos.add(diaryInfo);
            if (adapter == null) {
                DiaryAdapter adapter = new DiaryAdapter(DiaryActivity.this, diaryInfos);
                rlv_content.setAdapter(adapter);
            } else {
                adapter.notifyDataSetChanged();
            }
        }
    }
}
